<template>
  <div class="login">
    <vue-particles
        class="login-bg"
        color="#66ffff"
        :particleOpacity="0.9"
        :particlesNumber="100"
        shapeType="circle"
        :particleSize="4"
        linesColor="#A0A0A0"
        :linesWidth="1"
        :lineLinked="true"
        :lineOpacity="0.4"
        :linesDistance="150"
        :moveSpeed="3"
        :hoverEffect="true"
        hoverMode="grab"
        :clickEffect="true"
        clickMode="push"
    >
    </vue-particles>
    <div class="loginBody">
      <div class="loginDiv">
        <div class="login-content">
          <h1 class="login-title">用户登录</h1>
          <el-form :model="loginForm" label-width="100px"
                   :rules="rules" ref="loginForm">
            <el-form-item prop="userNum">
            <span slot="label">
              <span style="color: #bbb5b5">账号</span>
            </span>
              <el-input style="width: 200px" type="text" v-model="loginForm.userNum"
                        autocomplete="off" size="small" placeholder="请输入账号或手机号"></el-input>
            </el-form-item>
            <el-form-item prop="userPassword">
            <span slot="label">
              <span style="color: #bbb5b5">密码</span>
            </span>
              <el-input style="width: 200px" type="password" v-model="loginForm.userPassword"
                        show-password autocomplete="off" size="small" @keyup.enter.native="confirm" placeholder="请输入密码"></el-input>
            </el-form-item>
            <el-form-item prop="authCode">
            <span slot="label">
              <span style="color: #bbb5b5">验证码</span>
            </span>
              <el-input style="width: 200px" type="text" v-model="loginForm.userCode"
                        autocomplete="off" size="small" placeholder="请输入验证码"></el-input>
              <img :src="imageCode" @click="getKaptcha" width="110px"/>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon='el-icon-check' @click="confirm">登 录</el-button>
              <el-button style="margin-left: 10px" type="warning" icon='el-icon-circle-plus-outline' @click="add">注 册
              </el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>
    <el-dialog
        title="注册"
        :visible.sync="centerDialogVisible"
        :append-to-body="true"
        width="30%"
        class="dialog1"
        center>
      <el-form ref="form" :rules="zcrules" :model="form" label-width="80px">
        <el-form-item label="账号" prop="userNum">
          <el-col :span="20">
            <el-input v-model="form.userNum" ></el-input>
          </el-col>
        </el-form-item>
        <el-form-item label="名字" prop="userName">
          <el-col :span="20">
            <el-input v-model="form.userName" ></el-input>
          </el-col>
        </el-form-item>

        <el-form-item label="密码" prop="userPassword" >
          <el-col :span="20">
            <el-input v-model="form.userPassword" type="password"></el-input>
          </el-col>
        </el-form-item>
        <el-form-item label="年龄" prop="userAge">
          <el-col :span="20">
            <el-input v-model="form.userAge" ></el-input>
          </el-col>
        </el-form-item>
        <el-form-item label="性别" prop="userSex">
          <el-radio-group v-model="form.userSex">
            <el-radio label="1">男</el-radio>
            <el-radio label="2">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="社团" prop="cid" >
          <el-col :span="20">
            <el-select v-model="form.cid" filterable placeholder="请选择社团" class="select1">
              <el-option
                  v-for="item in cNameData"
                  :key="item.cid"
                  :label="item.cname"
                  :value="item.cid">
              </el-option>
            </el-select>
          </el-col>
        </el-form-item>
        <el-form-item label="电话" prop="userPhone">
          <el-col :span="20">
            <el-input v-model="form.userPhone" ></el-input>
          </el-col>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer" >
    <el-button @click="centerDialogVisible=false">取 消</el-button>
    <el-button type="primary" @click="save">确 定</el-button>
        </span>
    </el-dialog>
  </div>
    <Player v-if="isMobile" />
  </div>
</template>


<script>
import Player from "./zw-player/player";
export default {
  name: "Login",
  components: {
    Player,
  },
  created() {
    this.loadCname();
    this.getKaptcha()
  },
  data(){
    const checkAge = (rule, value, callback) => {
      if (value > 150) {
        callback(new Error('年龄输入过大'));
      } else {
        callback();
      }
    };
    const checkDuplicate = (rule, value, callback) => {
      if (this.form.userId) {
        return callback();
      }
      this.$axios.get(this.$httpUrl + "/user/findByNo?userNum=" + this.form.userNum).then(res => res.data).then(res => {
        if (res.code != 200) {
          callback()
        } else {
          callback(new Error('账号已经存在'));
        }
      })
    };
    return{
      centerDialogVisible:false,
      imageCode: '',
      uuid: '',
      cNameData:[],
      loginForm:{
        userNum:'',
        userPassword:'',
        uuid: '',
        userCode:''
      },
      form: {
        userId:'',
        userName:'',
        userNum:'',
        userPassword:'',
        userAge:'',
        userPhone:'',
        userSex:'0',
        cid:'',
        roleId:''
      },
      rules:{
        userNum: [
          { required: true, message: '请输入账号', trigger: 'blur' }
        ],
        userPassword: [
          { required: true, message: '请输密码', trigger: 'blur' }
        ],
      },
      zcrules:{
        userNum: [
          { required: true, message: '请输入账号', trigger: 'blur' },
          { min: 5, max: 18, message: '长度在 6 到 18 个字符', trigger: 'blur' },
          {validator:checkDuplicate,trigger: 'blur'}
        ],
        userName: [
          { required: true, message: '请输入名字', trigger: 'blur' },
        ],
        userPassword: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 18, message: '长度在 6 到 18 个字符', trigger: 'blur' }
        ],
        userAge: [
          {required: true, message: '请输入年龄', trigger: 'blur'},
          {min: 1, max: 3, message: '⻓度在 1 到 3 个位', trigger: 'blur'},
          {pattern: /^([1-9][0-9]*){1,3}$/,message: '年龄必须为正整数字',trigger: "blur"},
          {validator:checkAge,trigger: 'blur'}
        ],
        userPhone: [
          {required: true,message: "手机号不能为空",trigger: "blur"},
          {pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: "请输入正确的手机号码", trigger: "blur"}
        ]
      }
    }
  },
  methods:{
    isMobile() {
      const flag = navigator.userAgent.match(
          /(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i
      );
      return flag;
    },
    getKaptcha() {
      this.$axios.get(this.$httpUrl + '/user/kaptcha').then(res => res.data).then(res => {
        console.log(res)
        if (res.code == 200) {
          this.loginForm.uuid = res.data.uuid
          this.imageCode = res.data.image
        } else {
          alert("获取验证码错误")
        }
      })
    },
    save(){
      this.$axios.get(this.$httpUrl+'/user/checkadmin?cId='+this.form.cid).then(res=>res.data).then(res=>{
        if (res.code==200){
          this.form.roleId = '2'
          this.dosave()
        }else{
          this.form.roleId = '1'
          this.dosave()
        }
      })
    },
    loadCname(){
      this.$axios.get(this.$httpUrl+'/community/list').then(res=>res.data).then(res=>{
        console.log(res)
        if (res.code==200){
          this.cNameData=res.data
          //过滤管理员
          let id = this.cNameData.findIndex(item => {
            if (item.cid == '1') {
              return true
            }
          })
          this.cNameData.splice(id, 1)
        }else{
          alert("获取数据失败")
        }
      })
    },
    resetForm(){
      this.$refs.form.resetFields();
    },
    add(){

      this.centerDialogVisible=true
      this.disabled_index = false
      this.$nextTick(()=>{
        this.resetForm()
      })
    },
    dosave(){
      this.form.userPassword = this.$md5(this.form.userPassword)
      this.$axios.post(this.$httpUrl+'/user/add',this.form).then(res=>res.data).then(res=>{
        console.log(res)
        if (res.code==200){
          this.$message({
            showClose: true,
            message: '注册成功',
            type: 'success'
          });
          this.centerDialogVisible=false
        }else{
          this.$message({
            showClose: true,
            message: '注册失败',
            type: 'error'
          });
        }
      })
    },
    confirm() {
      this.$refs.loginForm.validate((valid) => {
        if (valid) { //valid成功为true，失败为false
          //去后台验证用户名密码
          this.loginForm.userPassword = this.$md5(this.loginForm.userPassword)
          this.$axios.post(this.$httpUrl + '/user/login', this.loginForm).then(res => res.data).then(res => {
            console.log(res)
            if (res.code == 200) {
              //存储
              console.log(res.data.user)
              sessionStorage.setItem("CurUser", JSON.stringify(res.data.user))
              //登录提示框
              this.$message({
                type: 'success',
                message: '登录成功'
              })
              console.log(res.data.menu)
              this.$store.commit("setMenu", res.data.menu)
              //跳转到主页
              this.$router.replace('/Index');
            } else {
              alert(res.data.info);
              this.loginForm.userPassword = ''
              this.loginForm.userCode = ''
              this.getKaptcha()
              return false;
            }
          });
        }
      });
    }
  }
}
</script>

<style scoped>
.login {
  background: url("../assets/bg.jpg") no-repeat;
  background-size: 100% 100%;
  position: fixed; /* 充满全屏 */
  height: 100%;
  width: 100%;
}

.loginDiv {
  position: absolute;
  top: 45%;
  left: 50%;
  margin-top: -200px;
  margin-left: -250px;
  width: 450px;
  height: 450px;
  background: #fff;
  border-radius: 5%;
  backdrop-filter: blur(10px);
  background: rgba(50, 50, 50, 0.3);
}

.login-bg {
  width: 100%;
  height: 100%;
  position: absolute;
  display: flex;
}

.login-title {
  margin: 20px 0;
  text-align: center;
}

.login-content {
  width: 400px;
  height: 350px;
  position: absolute;
  top: 25px;
  left: 25px;
}
</style>